package com.example.lotterysystem.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/1/27
 */
@Slf4j
@Configuration
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 设置值
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error("RedisUtil error,set({},{}): ", key, value, e);
            return false;
        }
    }

    /**
     * 设置值并设置过期时间
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key, String value, Long time) {
        try {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("RedisUtil error,set({},{},{}s): ", key, value, time, e);
            return false;
        }
    }

    /**
     * 获取值
     *
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            String s = redisTemplate.opsForValue().get(key);
            return StringUtils.hasText(key) ? s : null;
        } catch (Exception e) {
            log.error("RedisUtil error,get({}): ", key, e);
            return null;
        }
    }

    /**
     * 删除key
     *
     * @param key
     * @return
     */
    public boolean delete(String... key) {
        try {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    redisTemplate.delete(key[0]);
                } else {
                    redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
                }
            }
            return true;
        } catch (Exception e) {
            log.error("RedisUtil error,delete({}): ", key, e);
            return false;
        }
    }

    public boolean hasKey(String key) {
        try {
            Boolean b = redisTemplate.hasKey(key);
            return StringUtils.hasText(key) ? b : false;
        } catch (Exception e) {
            log.error("RedisUtil error,hasKey({}): ", key, e);
            return false;
        }
    }
}
